import datetime

from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from gathering.models import Gathering
from gathering.serializers import GatheringListserializer, GatheringDetailserializer
import pytz

utc = pytz.UTC


class GatheringsViewSet(ModelViewSet):
    queryset = Gathering.objects.all()

    # serializer_class = GatheringListserializer
    def get_serializer(self, *args, **kwargs):
        if self.action == 'list':
            return GatheringListserializer(*args, **kwargs)  # 列表

        elif self.action == 'retrieve':
            return GatheringDetailserializer(*args, **kwargs)  # 详情

        elif self.action == 'join':
            return GatheringDetailserializer(*args, **kwargs)

    @action(methods=['get'], detail=False)
    def list(self,request):
        gathering = Gathering.objects.all()
        serializer = self.get_serializer(gathering)

        page = self.paginate_queryset(gathering)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(gathering, many=True)
        return Response(serializer.data)

    @action(methods=['get'], detail=True)
    def retrieve(self,request,pk):
        gathering = Gathering.objects.get(id=pk)
        serializer = self.get_serializer(gathering)
        return Response(serializer.data)


class GatherJoinView(APIView):
    permission_classes = [IsAuthenticated, ]

    def post(self, request, pk):
        gathering = Gathering.objects.get(id=pk)
        user = request.user
        # 报名活动的所有用户
        gathering_user = gathering.users.all()
        if user not in gathering_user:
            gathering.users.add(user)

            data = {
                'message': '报名成功',
                'success': True
            }
            return Response(data)
        else:
            data = {
                'message': '您已经报过了，请不要重复报名',
                'success': False
            }

            return Response(data)
